<template>
  <el-main>
    <p></p>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="formInline.user" placeholder="请输入用户编号" clearable />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">
          <el-icon><Search /></el-icon>查询
        </el-button>
        <el-button type="primary" @click="dialogVisible = true">
          <el-icon><Plus /></el-icon>添加
        </el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="dialogVisible" title="添加" width="500">
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="auto"
        style="max-width: 600px"
      >
        <el-form-item label="用户编号" prop="userId">
          <el-input v-model="form.userId" />
        </el-form-item>
        <el-form-item label="用户姓名" prop="realname">
          <el-input v-model="form.realname" />
        </el-form-item>
        <el-form-item label="用户账号" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="用户密码" prop="pwd">
          <el-input v-model="form.pwd" type="password" />
        </el-form-item>
        <el-form-item label="用户地址" prop="place">
          <el-input v-model="form.place" />
        </el-form-item>
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="出生日期" prop="birth">
          <el-input v-model="form.birth" />
        </el-form-item>
        <el-form-item label="余额" prop="balance">
          <el-input v-model="form.balance" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmitAdd"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>

    <p></p>
    <el-table
      :data="tableData"
      class="table"
      @selection-change="handleSelectionChange"
      style="width: 99%"
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="用户编号" prop="userId" />
      <el-table-column label="用户姓名" prop="realname" />
      <el-table-column label="用户账号" prop="username" />
      <el-table-column label="用户密码" prop="pwd" />
      <el-table-column label="用户地址" prop="place" />
      <el-table-column label="联系方式" prop="phone" />
      <el-table-column label="出生日期" prop="birth" />
      <el-table-column label="余额" prop="balance" />
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button
            type="primary"
            :icon="Edit"
            size="small"
            @click="
              handleEdit(scope.$index, scope.row);
              dialogVisibleEdit = true;
            "
          />
          <el-button
            size="small"
            type="danger"
            :icon="Delete"
            @click="handleDelete(scope.$index, scope.row)"
          >
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisibleEdit" title="修改" width="500">
      <el-form :model="edit" label-width="auto" style="max-width: 600px">
        <el-form-item label="用户编号">
          <el-input v-model="edit.userId" />
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="edit.realname" />
        </el-form-item>
        <el-form-item label="用户账号">
          <el-input v-model="edit.username" />
        </el-form-item>
        <el-form-item label="用户密码">
          <el-input v-model="edit.pwd" type="password" />
        </el-form-item>
        <el-form-item label="用户地址">
          <el-input v-model="edit.place" />
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="edit.phone" />
        </el-form-item>
        <el-form-item label="出生日期">
          <el-input v-model="edit.birth" />
        </el-form-item>
        <el-form-item label="余额">
          <el-input v-model="edit.balance" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisibleEdit = false">取消</el-button>
          <el-button type="primary" @click="onSubmitEdit"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>

    <p></p>
    <div style="margin-top: 10px">
      <el-button mb-2 type="danger" @click="handleBatchDelete">批量删除</el-button>
      <br />
      <el-config-provider :locale="locale">
        <el-col span="8" :offset="5">
          <el-pagination
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            @current-change="handlePageChange"
            background
            layout="prev, pager, next, jumper"
          />
        </el-col>
      </el-config-provider>
    </div>
  </el-main>
</template>
<script lang="ts" setup>
import { reactive, ref, computed, onMounted } from "vue";
import axios from "axios";
import { Delete, Edit, Search, Plus } from "@element-plus/icons-vue";
import zhCn from "element-plus/dist/locale/zh-cn.mjs";
import en from "element-plus/dist/locale/en.mjs";

const language = ref("zh-cn");
const locale = computed(() => (language.value === "zh-cn" ? zhCn : en));

const toggle = () => {
  language.value = language.value === "zh-cn" ? "en" : "zh-cn";
};

interface User {
  userId: string;
  realname: string;
  username: string;
  pwd: string;
  place: string;
  phone: string;
  birth: string;
  balance: string;
}

const currentPage = ref(1);
const pageSize = ref(10); // 每页显示10条数据
const total = ref(0);
const tableData = ref<User[]>([]);
const selectedRows = ref<User[]>([]);

const formInline = reactive({
  user: "",
  region: "",
  date: "",
});

const onSubmit = async () => {
  try {
    const response = await axios.get("http://localhost:8080/user/list", {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        search: formInline.user,
      },
    });
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};

const dialogVisible = ref(false);

const form = reactive<User>({
  userId: "",
  realname: "",
  username: "",
  pwd: "",
  place: "",
  phone: "",
  birth: "",
  balance: "",
});

const rules = reactive({
  userId: [{ required: true, message: "请输入用户编号", trigger: "blur" }],
  realname: [{ required: true, message: "请输入用户姓名", trigger: "blur" }],
  username: [{ required: true, message: "请输入用户账号", trigger: "blur" }],
  pwd: [{ required: true, message: "请输入用户密码", trigger: "blur" }],
  phone: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
    { pattern: /^[0-9]+$/, message: "联系方式必须是数字", trigger: "blur" },
  ],
  birth: [{ required: true, message: "请输入出生日期", trigger: "blur" }],
  balance: [
    { required: true, message: "请输入余额", trigger: "blur" },
    { pattern: /^[0-9]+$/, message: "余额必须是数字", trigger: "blur" },
  ],
});

const dialogVisibleEdit = ref(false);

const edit = reactive<User>({
  userId: "",
  realname: "",
  username: "",
  pwd: "",
  place: "",
  phone: "",
  birth: "",
  balance: "",
});

const handleEdit = (index: number, row: User) => {
  Object.assign(edit, row);
  dialogVisibleEdit.value = true;
};

const handleDelete = async (index: number, row: User) => {
  try {
    await axios.delete(`http://localhost:8080/user/${row.userId}`);
    tableData.value.splice(index, 1);
    console.log(`Deleted row with id: ${row.userId}`);
  } catch (error) {
    console.error("Error deleting user:", error);
  }
};

const handleSelectionChange = (selection: User[]) => {
  selectedRows.value = selection;
};

const handleBatchDelete = async () => {
  const ids = selectedRows.value.map((row) => row.userId);
  if (ids.length === 0) {
    alert("请选择要删除的用户");
    return;
  }
  try {
    await axios.post("http://localhost:8080/user/batchDelete", { ids });
    tableData.value = tableData.value.filter((row) => !ids.includes(row.userId));
    console.log(`Deleted rows with ids: ${ids}`);
  } catch (error) {
    console.error("Error deleting users:", error);
  }
};

const onSubmitAdd = async () => {
  const formRef = ref();
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await axios.post("http://localhost:8080/user/add", form);
        fetchData();
        dialogVisible.value = false;
        // 清空表单数据
        Object.keys(form).forEach((key) => {
          form[key] = "";
        });
      } catch (error) {
        console.error("Error adding user:", error);
      }
    } else {
      console.log("error submit!!");
      return false;
    }
  });
};

const onSubmitEdit = async () => {
  try {
    await axios.put(`http://localhost:8080/user/${edit.userId}`, edit);
    fetchData();
    dialogVisibleEdit.value = false;
  } catch (error) {
    console.error("Error updating user:", error);
  }
};

const fetchData = async () => {
  try {
    const response = await axios.get("http://localhost:8080/user/list", {
      params: {
        page: currentPage.value,
        size: pageSize.value,
        search: formInline.user,
      },
    });

    if (response.data) {
      tableData.value = response.data.data.records || [];
      total.value = response.data.data.total || 0;
    } else {
      console.error("Unexpected response structure:", response.data);
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error("Error fetching data:", error);
    tableData.value = [];
    total.value = 0;
  }
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
  fetchData();
};

onMounted(() => {
  fetchData();
});
</script>
<style scoped>
.table {
  width: 85%;
  margin-left: 10px;
  margin-top: 20px;
}
.pagination {
  margin-top: 20px;
  margin-left: 400px;
}
.switch {
  display: none;
}
</style>
